<?php
namespace App\Api\Controllers\Validators;

use App\Models\api\Classify;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Validator;

class ClassifyValidator
{
	/**
	 * 获取分类 数据验证
	 *
	 * @param Request $request
	 * @return mixed
	 * */
	public static function getClassify(Request $request)
	{
		$only = ['level','parent_id'];

		$rules = [
			'level' => 'regex:/^[1-2]$/',
		];

		$messages = [
			'level.regex' => '请选择分类级别',
			'parent_id.exists' => '分类不存在'
		];

		if ($request->get('parent_id')){

			$rules['parent_id'] = [
				Rule::exists('t_course_category', 'id')
					->where(function ($query) use($request){
						$where = [
							'status' => Classify::STATUS_NORMAL,
						];
						$query->where($where);
					}),
			];
		}
		$input = $request->only($only);

		$validator = Validator::make($input, $rules, $messages);
		if ($validator->fails())
			exit(json_encode(['info'=>$validator->errors()->first(),'code'=>'1002']));

		if ($input['level'] == 1)
			$input['parent_id'] = 0;

		unset($input['level']);

		$input['status'] = Classify::STATUS_NORMAL;

		return $input;

	}

}